package com.tornado.community.provider;

import com.alibaba.fastjson.JSON;
import com.tornado.community.dto.AccessTokenDto;
import com.tornado.community.dto.GitHubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Component
public class GitHubProvider {
    private static final String accessTokenUrl = "https://github.com/login/oauth/access_token";
    public static final MediaType JSON_TYPE
            = MediaType.get("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    public String getAccessToken(AccessTokenDto accessTokenDto) throws IOException {
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDto), JSON_TYPE);
        Request request = new Request.Builder()
                .url(accessTokenUrl)
                .addHeader("Accept", "application/json")
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        String responseString = Objects.requireNonNull(response.body(), "获取GitHub认证失败。").string();
        return (String) JSON.parseObject(responseString, Map.class).get("access_token");
    }

    public GitHubUser getGitHubUser(String accessToken) throws IOException {
        Request request = new Request.Builder().url("https://api.github.com/user?access_token=" + accessToken).build();
        Response response;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException("GitHub访问失败：" + e.getMessage());
        }
        String responseString = Objects.requireNonNull(response.body()).string();
        return JSON.parseObject(responseString, GitHubUser.class);
    }
}
